//
//  TSSTManagedGroup.m
//  SimpleComic
//
//  Created by Alexander Rauchfuss on 6/2/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "TSSTManagedGroup.h"
#import <XADMaster/XADArchive.h>
#import <Quartz/Quartz.h>
#import "TSSTImageUtilities.h"


@implementation TSSTManagedGroup


- (void) dealloc
{
    [groupLock release];
    [instance release];
    [super dealloc];
}


- (void)awakeFromInsert
{
    groupLock = [NSLock new];
    [super awakeFromInsert];
    instance = nil;
}


- (void)awakeFromFetch
{
    groupLock = [NSLock new];
    [super awakeFromFetch];
    instance = nil;
}


- (NSString *)name
{
    return [[self valueForKey: @"path"] lastPathComponent];
}


- (id)instance
{
    return nil;
}


- (NSData *)dataForPageIndex:(int)index
{
    return nil;
}

@end


@implementation TSSTManagedArchive


- (void) dealloc
{
    [archiveLock release];
    [super dealloc];
}



- (id)instance
{
    if (!instance)
    {
        instance = [[XADArchive alloc] initWithFile: [self valueForKey: @"path"]];
        [instance setDelegate: [NSApp delegate]];

        if([self valueForKey: @"password"])
        {
            [instance setPassword: [self valueForKey: @"password"]];
        }
    }
    return instance;
}


- (NSData *)dataForPageIndex:(int)index
{
    if(!archiveLock)
    {
        archiveLock = [NSLock new];
    }
    [groupLock lock];
    NSData * imageData = [[self instance] contentsOfEntry: index];
    [groupLock unlock];

    return imageData;
}


@end



@implementation TSSTManagedPDF


- (id)instance
{
    if (!instance)
    {
        instance = [[PDFDocument alloc] initWithData: [NSData dataWithContentsOfFile: [self valueForKey: @"path"]]];
    }
    return instance;
}



- (NSData *)dataForPageIndex:(int)index
{	
    [groupLock lock];
	PDFPage * page = [[self instance] pageAtIndex: index];
    [groupLock unlock];
	
//	NSLog(NSStringFromRect([page boundsForBox: kPDFDisplayBoxBleedBox]));
//	NSImage * pageImage = [[NSImage alloc] initWithSize:[page boundsForBox: kPDFDisplayBoxBleedBox];
//	NSImage * pageImage = [[NSImage alloc] initWithData: [page dataRepresentation]];
//	[pageImage setDataRetained: YES];
//	[pageImage setScalesWhenResized: YES];
//	NSImageRep * pageRep = [pageImage bestRepresentationForDevice: nil];
//	[pageImage setSize: NSMakeSize([pageRep pixelsWide], [pageRep pixelsHigh])];
	
	NSData * imageData = [[page dataRepresentation] retain];
//	[pageImage release];
    return [imageData autorelease];
}

@end


